package com.passioneffect.layoutflow {
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.geom.Point;
	
	import com.passioneffect.adapter.ContentMovieClipAdapter;
	import com.passioneffect.collection.Collection;
	import com.passioneffect.collection.Iterator;
	import com.passioneffect.layout.Layout;
	import com.passioneffect.layoutflow.LayoutFlow;	

	/**
	 * @author Passion Effect
	 */
	public class SimpleLayoutFlow implements LayoutFlow {
		public function layoutFlow(layout:Layout,viewList:Collection,items:Collection,container:DisplayObjectContainer,placeFunc:Function) : void {
			
			var total:int=layout.total;
			
			var mc : MovieClip;
			var adapter : ContentMovieClipAdapter;
			var clearList : Collection = new Collection();
			
			var p : Point;
			var interValue:Object;
			
			layout.beforeLoop();
			
			for(var i : int = 0;i <total;i++) {
				adapter = ContentMovieClipAdapter(items.getItemAt(i));
				if(!adapter)break;
				p = layout.draw(i);
				interValue=layout.getInterValue(i);
				
				if(p) {
					mc = MovieClip(adapter.getMovieClip({x:p.x, y:p.y}));
					placeFunc(mc, p,interValue);
					
				}else {
					//should remove
					mc = MovieClip(adapter.getMovieClip());	
					clearList.addItem(adapter);
				}
				
				if(!viewList.contains(adapter)) {
					//item not in view list, add it
					
					viewList.addItem(adapter);
					container.addChild(mc);
					mc.visible = true;
				}
			}
			
			//remove items that no need but in view list
			var itr : Iterator = clearList.iterator();
			while(itr.hasNext()) {
				adapter = ContentMovieClipAdapter(itr.next());
				adapter.removeMovieClip();
				viewList.removeItem(adapter);
			}
			
			layout.resetDepths(viewList);
			layout.onDraw(viewList);
			
		}
		
	}
}
